package com.foreveross.taskservice.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.dayatang.domain.InstanceFactory;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.foreveross.taskservice.application.task.mq.ITaskToMQApplication;
import com.foreveross.taskservice.infra.cfg.ConfigLoader;
import com.foreveross.taskservice.infra.cfg.PropertyUtils;
import com.foreveross.taskservice.infra.cfg.taskservice.TaskServicePropertiesLoader;
import com.foreveross.taskservice.infra.util.SpringUtil;
import com.foreveross.taskservice.taskcache.ITaskCacheFlush;


/**
 * 做一个自启动监听，主要是Quartz中无法做spring的注入操作。 在此类中加载InstanceFactory和加载配置文件
 * 
 * @author Administrator
 * 
 */
public class TaskStartupListener implements ServletContextListener {
	private static Logger log = LoggerFactory.getLogger(TaskStartupListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		log.info("[任务服务结束]");
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		boolean initClearTasks = PropertyUtils.getBooleanProperty(TaskServicePropertiesLoader.TASKSERVICE_INITSTARTUP_CLEAR_TASKS,
				TaskServicePropertiesLoader.FILE_NAME);
		if(initClearTasks){
			log.info("清理上次运行时的一些任务数据");
			try {
				this.clearAllTasks();
			} catch (Exception e) {
				log.error("清理出错:" + e.getMessage());
			}
		}
		Scheduler scheduler=(Scheduler) InstanceFactory.getInstance(Scheduler.class, "scheduler");
		try {
			scheduler.start();
			log.info("[quartz] 启动");
		} catch (SchedulerException e) {
			log.error(org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e));
			log.info("[quartz] 启动失败");
			System.exit(0);
		}
	}

	private void clearAllTasks() throws Exception{
		ITaskToMQApplication taskToMQApplication = InstanceFactory.getInstance(ITaskToMQApplication.class);
		ITaskCacheFlush taskCacheFlush = InstanceFactory.getInstance(ITaskCacheFlush.class);
		//清除MQ上所有数据
		taskToMQApplication.clearHistory();
		//清除所有Redis上内存数据
		taskCacheFlush.flushDB();
	}
}
